package com.luboyan.CBillbill.service.user.following.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luboyan.CBillbill.exception.ConditionException;
import com.luboyan.CBillbill.mapper.user.following.UserFollowingMapper;
import com.luboyan.CBillbill.dao.user.following.FollowingGroup;
import com.luboyan.CBillbill.dao.user.User;
import com.luboyan.CBillbill.dao.user.following.UserFollowing;
import com.luboyan.CBillbill.dao.user.UserInfo;
import com.luboyan.CBillbill.service.user.following.FollowingFGroupService;
import com.luboyan.CBillbill.service.user.following.UserFollowingService;
import com.luboyan.CBillbill.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.luboyan.CBillbill.util.enums.UserInfoEnum.USER_FOLLOWING_GROUP_TYPE_DEFAULT;

@Service
public class UserFollowingServiceImpl implements UserFollowingService {

    @Autowired
    private UserFollowingMapper userFollowingMapper;

    @Autowired
    private FollowingFGroupService followingFGroupService;

    @Autowired
    private UserService userService;

    /**
     * 添加关注用户
     */
    @Override
    @Transactional
    public void addUserFollowings(UserFollowing userFollowing) {

        //1.先看groupId是否为空判断是不是默认的添加关注方式
        Long groupId = userFollowing.getGroupId();
        if (groupId == null) {
            //1.1为空就将groupId设置为默认分组的值
            FollowingGroup followingGroup = followingFGroupService.getByType(USER_FOLLOWING_GROUP_TYPE_DEFAULT.getParameter());
            userFollowing.setGroupId(followingGroup.getId());
        }
        //1.2不为空先判断组是否存在
        FollowingGroup followingGroup = followingFGroupService.getById(userFollowing.getGroupId());
        if (followingGroup == null) {
            throw new ConditionException("分组不存在！");
        }
        //1.3关注的用户是否存在
        Long followingId = userFollowing.getFollowingId();
        if(Objects.equals(followingId, userFollowing.getUserId())){
            throw new ConditionException("不能关注自己！");
        }
        User user = userService.getById(followingId);
        if (user == null) {
            throw new ConditionException("用户不存在！");
        }
        //1.4保存
        QueryWrapper<UserFollowing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userFollowing.getUserId())
                .eq("followingId", followingId);
        userFollowingMapper.delete(queryWrapper); //为了不写更新功能
        userFollowing.setCreateTime(new Date());
        userFollowingMapper.insert(userFollowing);

    }

    /**
     * 获取用户关注的分组信息
     */
    @Override
    public List<FollowingGroup> getUserFollowings(Long userId) {
        //1.先将用户的所有关注列表获取到，通过关注列表的followingId（对应关注用户的userId）查询所有关注用户的基本信息
        QueryWrapper<UserFollowing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        List<UserFollowing> userFollowings = userFollowingMapper.selectList(queryWrapper); //获取到的用户关注列表
        Set<Long> followingIds = new HashSet<>();
        for (UserFollowing userFollowing : userFollowings) {
            followingIds.add(userFollowing.getFollowingId());
        }
        List<UserInfo> userInfos = new ArrayList<>(); //获取到的用户关注列表的所有用户基本信息
        if (!followingIds.isEmpty()) {
            userInfos = userService.getUserInfoByIds(followingIds);
        }

        //2.将查询到的所有关注用户的基本信息通过followingId（对应关注用户的userId）放入获取到的用户关注列表中
        for (UserFollowing userFollowing : userFollowings) {
            for (UserInfo userInfo : userInfos) {
                if (userFollowing.getFollowingId().equals(userInfo.getUserId())) {
                    userFollowing.setUserInfo(userInfo);
                    break;
                }
            }
        }

        //3.将用户的所有关注组获取到
        List<FollowingGroup> groupList = followingFGroupService.getFollowingGroupByUserId(userId);

        //先添加一个全部关注的分组包括所有关注用户的基本信息
        FollowingGroup allGroup = new FollowingGroup();
        allGroup.setName("全部关注");
        allGroup.setUserInfoList(userInfos);
        List<FollowingGroup> result = new ArrayList<>();
        result.add(allGroup);

        //4.将2中的已经填充好用户基本信息的用户关注列表，通过groupId（对应分组表的id）将其放入对应关注组中
        for (FollowingGroup followingGroup : groupList) {
            List<UserInfo> userInfoList = new ArrayList<>();
            for (UserFollowing userFollowing : userFollowings) {
                if (followingGroup.getId().equals(userFollowing.getGroupId())) {
                    userInfoList.add(userFollowing.getUserInfo());
                }
            }
            followingGroup.setUserInfoList(userInfoList);
            result.add(followingGroup);
        }
        return result;
    }

    /**
     * 获取当前登录用户的粉丝列表
     */
    @Override
    public List<UserFollowing> getUserFans(Long userId) {

        //1.通过当前用户的userId去匹配所有用户关注表的followingId查询所有粉丝用户
        QueryWrapper<UserFollowing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("followingId", userId);
        List<UserFollowing> userFans = userFollowingMapper.selectList(queryWrapper);

        //2.通过userFans中的userId去获取粉丝的基本用户信息
        Set<Long> followingIds = new HashSet<>();
        for (UserFollowing userFollowing : userFans) {
            followingIds.add(userFollowing.getUserId());
        }

        List<UserInfo> userInfos = new ArrayList<>();
        if (!followingIds.isEmpty()) {
            userInfos = userService.getUserInfoByIds(followingIds);
        }

        //3.判断粉丝中是否有互关的情况
        queryWrapper.clear();
        queryWrapper.eq("userId", userId);
        List<UserFollowing> userFollowings = userFollowingMapper.selectList(queryWrapper); //当前用户的关注用户列表
        for (UserFollowing useFan : userFans) {
            for (UserInfo userInfo : userInfos) {
                if (useFan.getUserId().equals(userInfo.getUserId())) {
                    userInfo.setFollowed(false);
                    useFan.setUserInfo(userInfo);
                }
            }
            for (UserFollowing userFollowing : userFollowings) {
                if (userFollowing.getFollowingId().equals(useFan.getUserId())) {
                    useFan.getUserInfo().setFollowed(true);
                }
            }
        }
        return userFans;
    }
}
